/*
 * Copyright 2013-2014 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.coder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.util.ConvertUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 
 * @author max.zheng
 * @create 2014-10-26下午8:48:10
 * @since 1.0
 * @see
 */
public class CodeCreater
{
	private static Configuration cfg = null;

	// 创建数据模型
	static Map<String, Object> rootMap = new HashMap<String, Object>();
	
	public static Map<String, String> tableMap = new HashMap<String, String>();
	// 模块名称
	static String moduleName = "message";
	// 模型名称
	static String modelName = "new";
	// 表名�?
	static String tableName = moduleName.toUpperCase() + "_" + modelName.toUpperCase();

	//	static String fileUrl = new File("").getAbsolutePath() + "/WebRoot/temp/";//"F:/testTempleat";
	public static String fileUrl = "F:/testTempleat";
	
	public static String vueFileUrl = "F:/testTempleat";

	public static final String DAO = "dao";

	public static final String SERVICE = "service";

	public static final String CONTROLLER = "controller";

	public static final String ENTITY = "entity";

	public static final String BIZ = "biz";

	public static final String VO = "vo";
	
	public static final String MAINVUE = "vue";
	
	public static final String JS = "js";

	//	static String beanJavaName = modelName.substring(0, 1).toUpperCase()+ modelName.substring(1, modelName.length());

	static
	{
		rootMap.put("moduleName", moduleName);
		//		// 创建时间
		rootMap.put("createTime", "2014-12-15 15:23:39");
		rootMap.put("modelName", modelName);
		rootMap.put("tableName", tableName);
		rootMap.put("modelBeanName", toUpperCaseFirstOne(modelName));

		List<CoderField> coderFields = new ArrayList<CoderField>();
		coderFields.add(new CoderField(modelName, "Long", "id", "ID", "", true, false));
		coderFields.add(new CoderField(modelName, "String", "name", "NAME", "名称", true, false));
		coderFields.add(new CoderField(modelName, "Date", "sendTime", "SEND_TIME", "发�?时间", true, true));
		coderFields.add(new CoderField(modelName, "String", "content", "CONTENT", "内容", false, false));
		rootMap.put("fields", coderFields);
	}

	public static boolean create(Coder coder, String checkedType)
	{
		boolean rs = true;
		rootMap.clear();
		List<CoderField> coderFields = new ArrayList<CoderField>();
		moduleName = coder.getModuleName();
		modelName = coder.getModelName();
		tableName = coder.getTableName();
		fileUrl = coder.getFilePath();
		vueFileUrl = coder.getVuefilePath();
		for (CoderField field : coder.getFields())
		{
			coderFields.add(field);
		}
		rootMap.put("moduleName", moduleName);
		String vueModel = ConvertUtil.converUpperCaseFirst(tableName.replace(moduleName + "_", ""));
		
		String nnnString = ConvertUtil.converUpperCaseFirst(tableName.replace("_", "-"));
		
		String vvvString = vueModel.replace("_", "").toLowerCase();
		// 创建时间
		rootMap.put("createTime", "2014-12-15 15:23:39");
		rootMap.put("modelName", modelName);
		rootMap.put("tableName", tableName);
		rootMap.put("requestMapping", vvvString);
		rootMap.put("vueModel", vueModel);
		rootMap.put("vueTab", nnnString.toLowerCase());
		rootMap.put("fields", coderFields);

		try
		{
			init();
			String[] array = checkedType.split(",");
			for (String key : array)
			{
				createFole(key);
				switch (key)
				{
					case DAO:
						System.out.println("生成Dao文件");
						processDao();
						break;
					case SERVICE:
						System.out.println("生成SERVICE文件");
						processService();
						break;
					case CONTROLLER:
						System.out.println("生成CONTROLLER文件");
						processController(key);
						break;
					case ENTITY:
						System.out.println("生成ENTITY文件");
						processEntity(key);
						break;
					case BIZ:
						System.out.println("生成Biz文件");
						processBiz();
						break;
					case VO:
						System.out.println("生成VO文件");
						processVO(key);
						break;
					case MAINVUE:
						System.out.println("生成VUE文件");
						processVUE(key,nnnString);
						break;
					case JS:
						System.out.println("生成VUE文件");
						processJS(vvvString);
						break;
					default:
						break;
				}
			}
			//			processDao();
			//			processService();
			//			processModelItem();
			//			processController();

			//			processModelHtml();
			//			processModelEditHtml();

		}
		catch (Exception e)
		{
			e.printStackTrace();
			rs = false;
		}
		return rs;
	}

	//
	public static void main(String[] args)
	{
		try
		{
			//			init();
			//			processEntity();
			//			processModelItem();
			//			processController();
			//			processService();
			//			processDao();
			//		    String classPath = "F:/testTempleat/Dao/";
			//		    createFile(classPath);
			//			processModelHtml();
			//			processModelEditHtml();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

	}
	public static void processJS(String vvvString) throws Exception
	{
		Template template = cfg.getTemplate("js.ftl");
		String javaModelUrl = vueFileUrl + "/" + moduleName + "/" + toLowerCaseFirstOne(modelName) + "/" + toLowerCaseFirstOne(modelName) + ".js";
		File javaModelFile = new File(javaModelUrl);
		// 合并处理（模�?+ 数据模型�?
		template.process(rootMap, new OutputStreamWriter(new FileOutputStream(javaModelFile), "GB2312"));
	}
	public static void processVUE(String key,String mainName) throws Exception
	{
		Template template = cfg.getTemplate("main.ftl");
		String javaModelUrl = vueFileUrl + "/" + moduleName + "/" + toLowerCaseFirstOne(modelName) + "/" + modelName + ".vue";
		File javaModelFile = new File(javaModelUrl);
		// 合并处理（模�?+ 数据模型�?
		template.process(rootMap, new OutputStreamWriter(new FileOutputStream(javaModelFile), "GB2312"));
		
		template = cfg.getTemplate("listVue.ftl");
		javaModelUrl = vueFileUrl + "/" + moduleName + "/" + toLowerCaseFirstOne(modelName) + "/List" + modelName + ".vue";
		javaModelFile = new File(javaModelUrl);
		// 合并处理（模�?+ 数据模型�?
		template.process(rootMap, new OutputStreamWriter(new FileOutputStream(javaModelFile), "GB2312"));
		
		template = cfg.getTemplate("editVue.ftl");
		javaModelUrl = vueFileUrl + "/" + moduleName + "/" + toLowerCaseFirstOne(modelName) + "/Edit" + modelName + ".vue";
		javaModelFile = new File(javaModelUrl);
		// 合并处理（模�?+ 数据模型�?
		template.process(rootMap, new OutputStreamWriter(new FileOutputStream(javaModelFile), "GB2312"));
		
	}
	public static void processVO(String key) throws Exception
	{
		Template template = cfg.getTemplate("modelItem.ftl");
		String javaModelUrl = fileUrl + "/" + key + "/" + modelName + "Vo.java";
		File javaModelFile = new File(javaModelUrl);
		// 合并处理（模�?+ 数据模型�?
		template.process(rootMap, new OutputStreamWriter(new FileOutputStream(javaModelFile), "GB2312"));
	}

	public static void processEntity(String key) throws Exception
	{
		Template template = cfg.getTemplate("model.ftl");
		String javaModelUrl = fileUrl + "/" + key + "/" + modelName + ".java";
		File javaModelFile = new File(javaModelUrl);
		// 合并处理（模�?+ 数据模型�?
		template.process(rootMap, new OutputStreamWriter(new FileOutputStream(javaModelFile), "GB2312"));
	}

	/**
	 * 
	 * @author max.zheng
	 * @throws Exception
	 * @create 2014-10-28下午11:05:42
	 * @modified by
	 */
	//	private static void processModelEditHtml() throws Exception {
	//		Template template = cfg.getTemplate("editModelHtml.ftl");
	//		String javaModelUrl = fileUrl + "/edit" + toUpperCaseFirstOne(modelName) + ".html";
	//		File javaModelFile = new File(javaModelUrl);
	//		template.process(rootMap, new OutputStreamWriter(new FileOutputStream(
	//				javaModelFile),"UTF-8"));
	//	}

	/**
	 * 
	 * @author max.zheng
	 * @throws Exception
	 * @create 2014-10-28下午11:05:38
	 * @modified by
	 */
	//	private static void processModelHtml() throws Exception {
	//		Template template = cfg.getTemplate("modelHtml.ftl");
	//		String javaModelUrl = fileUrl + "/" + modelName + ".html";
	//		File javaModelFile = new File(javaModelUrl);
	//		template.process(rootMap, new OutputStreamWriter(new FileOutputStream(
	//				javaModelFile)));
	//	}

	/**
	 * 
	 * @author max.zheng
	 * @throws Exception
	 * @create 2014-10-28下午11:05:33
	 * @modified by
	 */
	private static void processDao() throws Exception
	{
		Template template = cfg.getTemplate("modelDao.ftl");
		String javaModelUrl = fileUrl + "/dao/" + modelName + "Dao.java";
		File javaModelFile = new File(javaModelUrl);
		OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(
				javaModelFile));
		template.process(rootMap, writer);

		template = cfg.getTemplate("IModelDao.ftl");
		javaModelUrl = fileUrl + "/dao/I" + modelName + "Dao.java";
		javaModelFile = new File(javaModelUrl);
		template.process(rootMap, new OutputStreamWriter(new FileOutputStream(
				javaModelFile)));

		writer.close();
	}
	
	private static void createFile(String path)
	{
		File file = new File(path);
		//如果文件夹不存在则创建  
		if (!file.exists() && !file.isDirectory())
		{
			System.out.println(path + "//不存在");
			file.mkdirs();
		}
		else
		{
			System.out.println(path + "//目录存在");
		}
	}
	
	public static void createFole(String key)
	{
		String path = fileUrl + "/" + key;
		switch (key)
		{
			case DAO:
				System.out.println("生成Dao文件");
				break;
			case SERVICE:
				System.out.println("生成SERVICE文件夹");
				String javaModelUrl = fileUrl + "/biz/service/";
				createFile(javaModelUrl);
				javaModelUrl = fileUrl + "/biz/service/impl/";
				createFile(javaModelUrl);
				break;
			case CONTROLLER:
				System.out.println("生成CONTROLLER文件夹");
				createFile(path);
				break;
			case ENTITY:
				System.out.println("生成ENTITY文件夹");
				createFile(path);
				break;
			case BIZ:
				System.out.println("生成Biz文件夹");
				break;
			case VO:
				System.out.println("生成VO文件夹");
				createFile(path);
				break;
			case MAINVUE:
				System.out.println("生成VUE文件夹");
				createFile(vueFileUrl + "/" + moduleName + "/" + toLowerCaseFirstOne(modelName) + "/");
				break;
			case JS:
				System.out.println("生成JS文件夹");
				createFile(vueFileUrl + "/" + moduleName + "/" + toLowerCaseFirstOne(modelName) + "/");
				break;
			default:
				break;
		}
	}

	/**
	 * 
	 * @author max.zheng
	 * @throws Exception
	 * @create 2014-10-28下午11:05:20
	 * @modified by
	 */
	private static void processService() throws Exception
	{
		Template template = cfg.getTemplate("modelService.ftl");
		String javaModelUrl = fileUrl + "/biz/service/" + modelName + "Service.java";
		File javaModelFile = new File(javaModelUrl);
		template.process(rootMap, new OutputStreamWriter(new FileOutputStream(javaModelFile), "GB2312"));

		template = cfg.getTemplate("modelServiceImpl.ftl");
		javaModelUrl = fileUrl + "/biz/service/impl/" + modelName + "ServiceImpl.java";
		javaModelFile = new File(javaModelUrl);
		template.process(rootMap, new OutputStreamWriter(new FileOutputStream(javaModelFile), "GB2312"));
	}

	/**
	 * 
	 * @author max.zheng
	 * @throws Exception
	 * @create 2014-10-28下午11:05:20
	 * @modified by
	 */
	private static void processBiz() throws Exception
	{
		Template template = cfg.getTemplate("biz.ftl");
		String javaModelUrl = fileUrl + "/biz/" + modelName + "Biz.java";
		File javaModelFile = new File(javaModelUrl);
		template.process(rootMap, new OutputStreamWriter(new FileOutputStream(
				javaModelFile)));

		template = cfg.getTemplate("Ibiz.ftl");
		javaModelUrl = fileUrl + "/biz/I" + modelName + "Biz.java";
		javaModelFile = new File(javaModelUrl);
		template.process(rootMap, new OutputStreamWriter(new FileOutputStream(
				javaModelFile)));
	}

	/**
	 * 
	 * @author max.zheng
	 * @create 2014-10-28下午11:05:17
	 * @modified by
	 */
	private static void processController(String key) throws Exception
	{
		Template template = cfg.getTemplate("modelController.ftl");
		String javaModelUrl = fileUrl + "/" + key + "/" + modelName + "Controller.java";
		File javaModelFile = new File(javaModelUrl);
		// 合并处理（模�?+ 数据模型�?
		template.process(rootMap, new OutputStreamWriter(new FileOutputStream(javaModelFile), "GB2312"));
	}

	// 初始化工�?
	public static void init() throws Exception
	{
		String classPath = CodeCreater.class.getResource("/").getPath();
		classPath = classPath.replaceAll("%20", " ");// 进行空格处理
		cfg = new Configuration();
		// 设置模板文件位置
		cfg.setDirectoryForTemplateLoading(new File(classPath + "/template/"));
		File javaModelFile = new File(fileUrl);
		if (!javaModelFile.exists())
		{
			javaModelFile.mkdir();
		}
	}

	/**
	 * 
	 * @author max.zheng
	 * @throws Exception
	 * @create 2014-10-28下午10:53:19
	 * @modified by
	 */
	//	private static void processModelItem() throws Exception {
	//		Template template = cfg.getTemplate("modelItem.ftl");
	//		String javaModelUrl = fileUrl + "/" + toUpperCaseFirstOne(modelName) + "Item.java";
	//		File javaModelFile = new File(javaModelUrl);
	//		// 合并处理（模�?+ 数据模型�?
	//		template.process(rootMap, new OutputStreamWriter(new FileOutputStream(
	//				javaModelFile)));
	//	}
	//	
	public static String toUpperCaseFirstOne(String name)
	{
		char[] ch = name.toCharArray();
		for (int i = 0; i < ch.length; i++)
		{
			if (i == 0)
			{
				ch[0] = Character.toUpperCase(ch[0]);
			}
			else
			{
				ch[i] = Character.toLowerCase(ch[i]);
			}
		}
		StringBuffer a = new StringBuffer();
		a.append(ch);
		return a.toString();
	}
	
	public static String toLowerCaseFirstOne(String name)
	{
		char[] ch = name.toCharArray();
		for (int i = 0; i < ch.length; i++)
		{
			if (i == 0)
			{
				ch[0] = Character.toLowerCase(ch[0]);
			}
			else
			{
				ch[i] = ch[i];
			}
		}
		StringBuffer a = new StringBuffer();
		a.append(ch);
		return a.toString();
	}
}
